package org.example.finalobj;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * @author zhengdp
 * @Description 日期转换问题 ： 日期转换类 线程不安全
 * 在多线程下 使用 formar()方法，会出现问题
 * @Date 2022/11/29 22:41
 * @Created by zhengdp
 */
@Slf4j(topic = "c.DateParseFinalTest")
public class DateParseFinalTest {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) {
        //unsafeParse();
        //safeParse();
        safeParse1();
    }

    /**
     * 引入新的对象来实现 DateTimeFormatter
     */
    private static void safeParse1() {
        DateTimeFormatter stf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    TemporalAccessor parse = stf.parse("1999-05-21");
                    log.info("{}",parse);
                } catch (Exception e) {
                    log.error("e", e);
                }
            }).start();
        }
    }

    /**
     * 加锁解决 多线程调用问题
     */
    private static void safeParse() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (sdf) {
                    try {
                        log.info("{}", sdf.parse("1999-05-21"));
                    } catch (Exception e) {
                        log.error("e", e);
                    }
                }
            }).start();
        }
    }

    private static void unsafeParse() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    log.info("{}", sdf.parse("1999-05-21"));
                } catch (Exception e) {
                    log.error("e", e);
                }
            }).start();
        }
    }

}
